/*
 * @Descripttion: redux中的applyMiddleware模块
 * @Author: lukasavage
 * @Date: 2021-11-28 10:42:29
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-11-28 12:27:26
 */


/**
 * redux的中间件都是三阶函数
 * @param {Function} logger 中间件，可以传入多个
 * @returns 改写dispatch方法后的store
 */
import compose from './compose'
function applyMiddleware(...middlewares) {
    return function (createStore) {
        return function (reducer, preloadedState) {
            let store = createStore(reducer, preloadedState);
            let dispatch;
            let middlewareAPI = {
                getState: store.getState,
                dispatch: (action) => dispatch(action)    
            }
            const chain = middlewares.map(item=>item(middlewareAPI));
            dispatch = compose(...chain)(store.dispatch);
            dispatch = middlewares(middlewareAPI)(store.dispatch);
            return {
                ...store,
                dispatch
            };
        }
    }
}
export default applyMiddleware;